//
//  MapViewController.m
//  We365
//
//  Created by Pham Khuong Duy on 12/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MapViewController.h"
#import "MainViewController.h"
#import "Utilities.h"

@implementation MapViewController
@synthesize webView;
@synthesize item;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithItem:(Item *)i
{
    self = [super init];
    [self setItem:[i retain]];
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    CLLocation *location = [MainViewController getLocation];
    
    if(location == nil)
    {
        return;
    }
    
    NSMutableString *html = [NSMutableString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] encoding:NSUTF8StringEncoding error:nil];
    
    NSString *edited = [html stringByReplacingOccurrencesOfString:@"(0, 0)//A" withString:[NSString stringWithFormat:@"(%f,%f);", location.coordinate.latitude, location.coordinate.longitude]];
    
    edited = [edited stringByReplacingOccurrencesOfString:@"(0, 0)//B" withString:[NSString stringWithFormat:@"(%f,%f);", item.Latitude, item.Longitude]];
    
    [edited writeToFile:[Utilities getFilePath:@"index.html"] atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    NSURL *url = [NSURL fileURLWithPath:[Utilities getFilePath:@"index.html"]];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [webView loadRequest:requestObj];
}

- (void)viewDidUnload
{
    [self setItem:nil];
    [self setWebView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [item release];
    [webView release];
    [super dealloc];
}

- (NSString *)title
{
    return item.ItemName;
}
@end